package com.fyzk.activity.setting;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.App;
import com.fyzk.bean.FeedbackListBean;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.utils.AppUtil;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.RefreshListView;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.StringResultBean;

public class FeedbackActivity extends BaseActivity implements RefreshListView.OnRefreshListener {

    private TopTitleView topView;
    private TextView tishi_tv;
    //信息列表
//    private RefreshListView listView;
    private ListView listView;
    private FeedbackListAdapter adapter;
    //信息集合
    private List<FeedbackListBean> infors = new ArrayList<FeedbackListBean>();
    private TextView addFeedback;   // 新增反馈按钮

    private boolean requestType = false;    //请求方式：true加载更多，false首次请求或刷新

    private int min_id = 0;

    // 客服电话
    private String servicePhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fankui);

        servicePhone = AppUtil.getFormatStr(
                App.getContext().getResources().getString(R.string.feedback_tishi),
                MySharedPreferences.getInstance().getServiceQQ());

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        min_id = 0;
//        getFeedback();
    }

    /**
     * 初始化
     */
    private void initView() {

        topView = (TopTitleView) findViewById(R.id.fankui_top_rl);
        topView.setOnTitleClickListener(this);
        tishi_tv = (TextView) findViewById(R.id.feedback_tishi);
//        listView = (RefreshListView) findViewById(R.id.fankui_list);
        listView = (ListView) findViewById(R.id.fankui_list);
//        listView.setItemsCanFocus(false);
//        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//        listView.setOnRefreshListener(this);
        addFeedback = (TextView) findViewById(R.id.feedback_add);

        final EditText feed = findViewById(R.id.et_feed);
        TextView commit = (TextView) findViewById(R.id.tv_commit);

        adapter = new FeedbackListAdapter(getContext(), infors, servicePhone);
        listView.setAdapter(adapter);

        tishi_tv.setText(servicePhone);

        addFeedback.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), AddFeedbackActivity.class);
                startActivity(intent);

            }
        });

        commit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(feed.getText().toString())){
                    feed.setText("");
                    showToast("已提交");
                }else {
                    showToast("请输入您的意见");
                }
            }
        });
    }

    /**
     *  获取反馈列表
     */
    private void getFeedback() {
        long timestamp = System.currentTimeMillis();
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("user_mark", http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef.stringFromJNI() +
                    timestamp).getBytes()).getBytes()));
            data.put("min_id", min_id);
            data.put("max_id", 0);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FEEDBACKLIST);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FEEDBACKLIST, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 判断是否有网络
     */
    public static boolean isNetWorkConnected(final Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService
                (context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            return networkInfo.isAvailable();
        }

        Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("网络设置提醒");
        builder.setMessage("网络连接不可用，是否进行设置？");
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();

        return false;
    }


    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FEEDBACKLIST:
                List<FeedbackListBean> beans = JSON.parseArray(resultBean.getData(), FeedbackListBean.class);
//                if (beans != null && beans.size() > 0) {
//                    min_id = beans.get(beans.size()-1).getId();
//                }
//                if (requestType) {  // 加载更多
//                    if (beans.size() > 0) {
//                        jcInfors.addAll(beans);
//                        listView.hideFooterView();
//                    } else {
//                        listView.noMore();
//                    }
//                } else {
//                    jcInfors = beans;
//                    listView.hideHeaderView();
//                    if (jcInfors.size() == 0) {
//                        listView.noMore();
//                    }
//                }
//                if (min_id == 0) {
//
//                    listView.noMore();
//                }

                infors = beans;
                if (infors != null) {
                    boolean isAnswer = false;
                    for (FeedbackListBean item: infors) {
                        if (item.getType() == 2) {
                            isAnswer = true;
                        } else if (isAnswer) {
                            item.isReply = true;
                        }
                    }
                }
                Collections.reverse(infors); // 倒序
//                listView.hideHeaderView();
//                listView.noMore("");

                adapter.setInfors(infors);
                requestType = false;

                adapter.notifyDataSetChanged();
                if (infors.size() > 0) {
                    listView.setSelection(ListView.FOCUS_DOWN);
                    tishi_tv.setVisibility(View.GONE);
                } else {
                    tishi_tv.setVisibility(View.VISIBLE);
                }
                break;
        }


    }

    @Override
    protected void onFailure(int requestCode) {
        super.onFailure(requestCode);
        if (!requestType) { // 下拉刷新或第一次请求
            infors.clear();

        } else {    // 加载更多
//            listView.noMore();

        }
        tishi_tv.setVisibility(View.VISIBLE);
        adapter.setInfors(infors);
    }

    @Override
    public void onDownPullRefresh() {
        min_id = 0;
        requestType = false;
        getFeedback();
    }

    @Override
    public void onLoadingMore() {
//        requestType = true;
//        getFeedback();
    }
}
